package com.emagic.manage.common.ui.base;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.ColorInt;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.bumptech.glide.Glide;
import com.emagic.manage.LifeApplication;
import com.emagic.manage.navigation.Navigator;

import dagger.android.AndroidInjection;
import dagger.android.support.DaggerAppCompatActivity;


/**
 * Activity 基类
 *
 * @author baoy
 * @version 1.0
 *          Create by 15/12/14 下午1:33
 */
public abstract class BaseActivity extends DaggerAppCompatActivity {


    //输入法管理器
    private InputMethodManager inputMethodManager = null;
    //Fragment 管理器
    private FragmentManager mFragmentManager = null;

    private Handler mHandler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
        AppManager.getDefault().addActivity(this);
        this.inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        this.mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    protected void onStop() {
        super.onStop();
        mHandler.post(() -> Glide.get(this).clearMemory());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getDefault().finishActivity(this);
    }

    @Override
    public void finish() {
        super.finish();
        hideSoftKeyboard();
    }

    /**
     * 键盘响应弹出
     *
     * @param editText
     */
    protected void requestSoftKeyboard(EditText editText) {

        editText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (editText.requestFocus()) {
                    // Show keyboard
                    if (inputMethodManager.showSoftInput(editText, 0)) {
                        editText.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                }


            }
        });
    }

    protected void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * activity 全屏显示
     */
    protected void requestFeatureFullScreen() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * activity 全屏显示,并且系统statusBar 与 navigationBar 显示透明<br/>
     * 此方法需要配合fitsSystemWindows属性使用
     */
    protected void requestFeatureNoTitleWithSystemBarTransparent() {
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }
    }

    /**
     * activity 全屏显示,并且系统statusBar显示透明<br/>
     * 此方法需要配合fitsSystemWindows属性使用
     */
    protected void requestFeatureNoTitleWithStatusBarTransparent() {
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    /**
     * 设置 statusBar 颜色
     *
     * @param colorInt
     */
    protected void setStatusBarColor(@ColorInt int colorInt) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.setStatusBarColor(colorInt);
        }
    }


    /**
     * 添加fragment
     *
     * @param fragment
     * @param containerViewId
     */
    protected void addFragment(Fragment fragment, @IdRes int containerViewId) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }
        mFragmentManager.beginTransaction()
                .add(containerViewId, fragment).commit();
    }


    /**
     * 添加fragment
     *
     * @param fragment
     * @param containerViewId
     * @param tag
     */
    protected void addFragment(Fragment fragment, @IdRes int containerViewId, String tag) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }

        mFragmentManager.beginTransaction()
                .add(containerViewId, fragment, tag).commit();

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏 * * @param v
     * * @param event * @return
     */
    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            return !(event.getX() > left
                    && event.getX() < right
                    && event.getY() > top
                    && event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 多种隐藏软件盘方法的其中一种 * * @param token
     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 替换fragment
     *
     * @param fragment
     * @param containerViewId
     */
    protected void replaceFragment(Fragment fragment, @IdRes int containerViewId) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }
        mFragmentManager.beginTransaction()
                .replace(containerViewId, fragment).commit();
    }

    /**
     * 替换fragment
     *
     * @param fragment
     * @param containerViewId
     * @param tag
     */
    protected void replaceFragment(Fragment fragment, @IdRes int containerViewId, String tag) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }

        mFragmentManager.beginTransaction()
                .replace(containerViewId, fragment, tag).commit();
    }

    /**
     * 隐藏fragment
     *
     * @param fragment
     */
    protected void hideFragment(Fragment fragment) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }

        mFragmentManager.beginTransaction().hide(fragment).commit();
    }

    /**
     * 显示fragment
     *
     * @param fragment
     */
    protected void showFragment(Fragment fragment) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }

        mFragmentManager.beginTransaction().show(fragment).commit();
    }

    /**
     * 移除fragment
     *
     * @param fragment
     */
    protected void removeFragment(Fragment fragment) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }

        mFragmentManager.beginTransaction().remove(fragment).commit();
    }

    protected void attachFragment(Fragment fragment) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }

        mFragmentManager.beginTransaction().attach(fragment).commit();
    }

    protected void detachFragment(Fragment fragment) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }

        mFragmentManager.beginTransaction().detach(fragment).commit();
    }

    /**
     * 返回 Navigator
     *
     * @return
     */
    public Navigator getNavigator() {
        return ((LifeApplication) getApplication()).getNavigator();
    }
}
